<template>
  <!-- 招聘的记录 -->
  <div>
    <div>
      <h1>招聘信息管理</h1>
    </div>
    <div class="search-container">
      <span class="search-label">公司：</span>
      <el-input
        v-model="companyName"
        placeholder="搜索公司"
        class="search-input"
      ></el-input>

      <span class="search-label">时间范围：</span>
      <el-date-picker
        v-model="time"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      >
      </el-date-picker>

      <span class="search-label">状态：</span>
      <!-- 搜索下拉框：value改为数字（匹配后端参数），label显示文字 -->
      <el-select
        v-model="status"
        placeholder="请选择状态"
        class="search-select"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-button type="primary" class="search-button" @click="handleSearch"
        >查询</el-button
      >
      <el-button type="success" class="search-button" @click="handleReset"
        >重置</el-button
      >
    </div>

    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 15px"
      :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
      }"
      :cell-style="{ textAlign: 'center' }"
      v-loading="dataLoading" element-loading-text="拼命加载中"
    >
      <el-table-column
        prop="companyName"
        label="公司名称"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="hrName"
        label="HR姓名"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="recruitName"
        label="职位名称"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="recruitDetail"
        label="职位简介"
        width="200"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="skillRequest"
        label="技能要求"
        width="200"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="startSalary"
        label="起始薪资"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="maxSalary"
        label="最高薪资"
        width="120"
      ></el-table-column>
      <el-table-column prop="payMethod" label="结算方式" width="120">
        <template slot-scope="scope">
          <!-- 直接在模板里判断：0=日结，1=周结... -->
          {{
            scope.row.payMethod === 0
              ? "日结"
              : scope.row.payMethod === 1
              ? "周结"
              : scope.row.payMethod === 2
              ? "月结"
              : scope.row.payMethod === 3
              ? "小时工"
              : scope.row.payMethod === 4
              ? "面议"
              : "未知方式"
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="welfareInfo"
        label="福利待遇"
        width="200"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="recruitDetail"
        label="工作职责"
        width="250"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="发布时间"
        width="150"
      ></el-table-column>

      <!-- 合并状态列和操作列 -->
      <el-table-column label="状态/操作" width="250" fixed="right">
        <template slot-scope="scope">
          <!-- 判断状态是否为未审核(0) - 只显示按钮 -->
          <template v-if="scope.row.status === 0">
            <el-button
              type="success"
              size="mini"
              style="margin-right: 8px"
              @click="confirmButtonHandle(scope.row)"
            >
              通过
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="rejectButtonHandler(scope.row)"
            >
              不通过
            </el-button>
          </template>

          <!-- 已通过或未通过状态 - 显示状态文字 -->
          <template v-else>
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import { selectAllAuditRecord, checkAuditRecord } from "@/api/auditRecord";
export default {
  created() {
    this.handleSearch();
  },
  methods: {
    // 加载数据方法
    async loadData(params) {
      //开启加载动画
      this.dataLoading=true;
      try {
        const response = await selectAllAuditRecord(params);
        console.log(response);
        this.tableData = response.data.list || [];
        this.total = response.data.total;
        //关闭加载动画
          this.dataLoading=false;
      } catch (error) {
        console.error("数据加载失败:", error);
        this.$message.error("加载数据失败，请稍后重试");
      }
    },

    // 审核通过：传当前行recruitId和status=1到后端
    confirmButtonHandle(row) {
      this.$confirm(`此操作将通过公司名为${row.companyName},是否继续？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          const checkData = {
            recruitId: row.recruitId,
            status: 1,
          };
          // 调用后端接口，参数为recruitId（当前行）和status=1（通过）
          checkAuditRecord(checkData).then((res) => {
            if (res.code == 200) {
              // 找到当前行并更新状态，实现按钮切换为“通过”文字
              const index = this.tableData.findIndex(
                (item) => item.recruitId === row.recruitId
              );
              if (index !== -1) {
                this.tableData[index].status = 1;
                this.$message.success("审核已通过");
              }
            }
          });
        })
        .catch(() => {
          this.$message.info("已取消通过操作");
        });
    },

    // 审核不通过：传当前行recruitId和status=2到后端
    rejectButtonHandler(row) {
      this.$confirm(`此操作将拒绝通过公司名为${row.companyName},是否继续？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          // 调用后端接口，参数为recruitId（当前行）和status=2（不通过）
          const checkData = {
            recruitId: row.recruitId,
            status: 2,
          };

          checkAuditRecord(checkData).then((res) => {
            if (res.code == 200) {
              // 找到当前行并更新状态，实现按钮切换为“未通过”文字
              const index = this.tableData.findIndex(
                (item) => item.recruitId === row.recruitId
              );
              if (index !== -1) {
                this.tableData[index].status = 2;
                this.$message.success(" 审核不通过 ");
              }
            }
          });
        })
        .catch(() => {
          this.$message.info("已取消拒绝操作");
        });
    },

    // 查询按钮点击事件
    handleSearch() {
      const params = {
        companyName: this.companyName,
        createTime: this.createTime,
        status: this.status,
        startTime: this.startTime,
        endTime: this.endTime,
        currentPage: this.currentPage, //当前页
        pageSize: this.pageSize, //每页大小
      };
      this.loadData(params);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handleSearch();
    },

    // 重置按钮逻辑
    handleReset() {
      this.companyName = "";
      this.time = [];
      this.status = "";
      this.startTime = null;
      this.endTime = null;
      this.createTime = "";
      this.handleSearch();
    },

    // 数字状态转文字
    getStatusText(status) {
      const statusTextMap = {
        0: "待审核",
        1: "通过",
        2: "未通过",
      };
      return statusTextMap[status] || "未知状态";
    },

    // 根据数字状态匹配标签类型
    getStatusType(status) {
      const statusTypeMap = {
        0: "info", // 待审核 → 蓝色 info
        1: "success", // 通过 → 绿色 success
        2: "danger", // 未通过 → 红色 danger
      };
      return statusTypeMap[status] || "info";
    },
  },
  watch: {
    // 监听时间范围变化，自动拆分到 startDate 和 endDate
    time(newVal) {
      if (newVal && newVal.length === 2) {
        this.startTime = newVal[0];
        this.endTime = newVal[1];
      } else {
        this.startTime = null;
        this.endTime = null;
      }
    },
  },
  data() {
    return {
      //加载状态
      dataLoading:false,
      companyName: "", // 搜索：公司名称
      time: [], // 搜索：时间范围（daterange默认数组）
      status: "", // 搜索：状态（值为数字0/1/2）
      tableData: [], // 表格数据源
      createTime: "", // 创建时间（搜索用）
      startTime: null, // 时间范围-开始时间
      endTime: null, // 时间范围-结束时间
      currentPage: 1, //当前页
      pageSize: 5, //每页大小
      total: 0,

      options: [
        // 状态下拉框选项
        { value: 0, label: "待审核" },
        { value: 1, label: "通过" },
        { value: 2, label: "未通过" },
      ],
    };
  },
};
</script>

<style scoped>
/* 原有样式不变，保留即可 */
.search-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 0;
}

.search-label {
  white-space: nowrap;
  font-size: 14px;
  color: #606266;
}

.search-input {
  width: 150px;
}

.el-table .el-tag {
  padding: 0 12px;
  height: 28px;
  line-height: 28px;
  font-size: 13px;
  min-width: 60px;
  text-align: center;
}

.search-select {
  width: 200px;
  margin-left: 10px;
}

.search-button {
  margin-left: 10px;
}

.el-table th {
  height: 70px !important;
  line-height: 70px !important;
  background-color: #f5f7fa !important;
}

.el-table {
  margin-top: 15px;
  font-size: 14px;
}

.el-table__body-wrapper {
  overflow-x: auto;
}

.pagination-left {
  margin-top: 10px;
  text-align: left;
}

@media screen and (max-width: 1600px) {
  .el-table {
    font-size: 13px;
  }
}
</style>